package link.cocoon.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import link.cocoon.common.resp.RespData;
import link.cocoon.security.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * @author xce
 * @date 2020/1/8  11:36
 */
@Slf4j
public class LoginHandler {

  /**
   * 登陆成功后，将token放入header中.
   */
  public static AuthenticationSuccessHandler successHandler() {
    return (request, response, authentication) -> {
      UserDetails userDetails = (UserDetails) authentication.getPrincipal();
      SecurityContextHolder.getContext().setAuthentication(authentication);
      Map<String, Object> map = new HashMap<>();
      map.put("token", JwtUtil.generateToken(userDetails.getUsername()));
      RespData<Map> respData = RespData.success("登陆成功", map);
      response.setContentType("application/json;charset=UTF-8");
      response.getWriter().write(new ObjectMapper().writeValueAsString(respData));
      log.info("{} 用户登陆成功！", userDetails.getUsername());
    };
  }

}
